import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Solution502 {

    public static class obj{
        int profit;
        int capital;

        public obj(int profit, int capital) {
            this.profit = profit;
            this.capital = capital;
        }
    }

    public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        ArrayList<obj> objs=new ArrayList<>();
        for (int i=0;i<profits.length;i++){
            objs.add(new obj(profits[i],capital[i]));
        }
        objs.sort(Comparator.comparingInt(a -> a.capital));
        PriorityQueue<obj> queue= new PriorityQueue<>((a, b) -> b.profit - a.profit);
        int point=0;
        for (int i = 0; i < k; i++) {
            while (point<objs.size()&&w>=objs.get(point).capital){
                queue.offer(objs.get(point));
                point++;
            }
            if (!queue.isEmpty()){
                obj o=queue.poll();
                w+=o.profit;
            }
        }
        return w;
    }

    public static void main(String[] args) {
        System.out.println(new Solution502().findMaximizedCapital(3,0,new int[]{1,2,3},new int[]{0,1,2}));
    }
}
